package saucaca.fragment;

import java.util.ArrayList;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;
import lemon.kenhnhacvn.VideoPlayActivity;

import org.json.JSONException;

import saucaca.Adapter.CommentAdapter;
import saucaca.CustomView.XListView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.CommentObject;
import saucaca.Object.HomeData;
import saucaca.Object.SongObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class CommentFragment extends Fragment implements saucaca.CustomView.XListView.IXListViewListener {
	Context context;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	private XListView listViewComnent;
	ImageView imgSend;
	EditText edtText;
	TextView txtStatus;
	String page = "0";
	String pageSize = "";
	int xpage = 0;
	boolean loadingMore;
	SongObject songObject;
	AlbumObject albumObject;
	String audioID = null;
	String type_SongAlbum;
	ArrayList<CommentObject> listComment;
	CommentAdapter adapter;
	AlertDialog alertDialog;
	RelativeLayout layout_comment;
	View empty_loading;
	ProgressBar empty_progress;
	ImageView empty_error, empty_noitem;
	TextView empty_text;
	float lastX;
	private SwipeRefreshLayout mSwipeLayout;

	public CommentFragment(Context context, SongObject id, String type_SongAlbum) {
		this.context = context;
		context = (Activity) context;
		this.songObject = id;
		this.type_SongAlbum = type_SongAlbum;
		audioID = songObject.getSONG_ID();
		adapter = new CommentAdapter(context, new ArrayList<CommentObject>());
	}

	public void update(SongObject id, String type_SongAlbum) {
		this.songObject = id;
		this.type_SongAlbum = type_SongAlbum;
		audioID = songObject.getSONG_ID();
		if (songObject.getFormNet())
			new listCommentService().execute(audioID);
		showView(songObject.getFormNet());
	}

	public CommentFragment(Context context, AlbumObject album, String type_SongAlbum) {
		this.context = context;
		this.type_SongAlbum = type_SongAlbum;
		audioID = album.getALBUM_ID();
		this.albumObject = album;
		adapter = new CommentAdapter(context, new ArrayList<CommentObject>());
	}

	public void update(AlbumObject album, String type_SongAlbum) {
		// this.songObject = id;
		this.type_SongAlbum = type_SongAlbum;
		audioID = album.getALBUM_ID();
		this.albumObject = album;
		new listCommentService().execute(audioID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View android = inflater.inflate(R.layout.comment, container, false);
		options = new DisplayImageOptions.Builder().showImageOnFail(R.drawable.ic_default).showStubImage(R.drawable.ic_default).showImageForEmptyUri(R.drawable.ic_default)
				.cacheInMemory().cacheOnDisc().build();
		findviewByID(android);
		if (songObject != null) {
			if (songObject.getFormNet())
				new listCommentService().execute(audioID);
			showView(songObject.getFormNet());
		}
		if (albumObject != null)
			new listCommentService().execute(audioID);
		return android;
	}

	void showView(boolean isOnline) {
		if (empty_loading != null) {
			if (isOnline) {
				layout_comment.setVisibility(View.VISIBLE);
				empty_loading.setVisibility(View.GONE);
			} else {
				layout_comment.setVisibility(View.GONE);
				empty_loading.setVisibility(View.VISIBLE);
				empty_progress.setVisibility(View.GONE);
				empty_error.setVisibility(View.VISIBLE);
				empty_noitem.setVisibility(View.GONE);
				empty_text.setVisibility(View.VISIBLE);
				empty_text.setText("Bình luận khi nghe nhạc Online!");
			}
		}
	}

	private void findviewByID(View view) {
		layout_comment=(RelativeLayout) view.findViewById(R.id.realativelayout_comment);
		listViewComnent = (XListView) view.findViewById(R.id.Comment_xListView);
		listViewComnent.setPullLoadEnable(true);
		listViewComnent.setXListViewListener(this);
		listViewComnent.setAdapter(adapter);

		empty_loading = view.findViewById(R.id.empty_loading);
		empty_progress = (ProgressBar) empty_loading.findViewById(R.id.empty_loading_progress);
		empty_text = (TextView) empty_loading.findViewById(R.id.empty_loading_text);
		empty_error = (ImageView) empty_loading.findViewById(R.id.empty_loading_Error);
		empty_noitem = (ImageView) empty_loading.findViewById(R.id.empty_loading_NoItem);

		imgSend = (ImageView) view.findViewById(R.id.comment_imgSend);
		edtText = (EditText) view.findViewById(R.id.comment_edtext);
		imgSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String user = PreferenceUtils.getString(context, TagName.KeyPreference_user);
				if (user != null) {
					String content = edtText.getText().toString();
					if (content != null && !content.equals(""))
						if (songObject != null && songObject.getFormNet()) {
							new sendCommentService().execute(content);
						} else
							new sendCommentService().execute(content);
					edtText.setText("");
				} else {
					alertDialog = new AlertDialog.Builder(context).setTitle("Bạn chưa đăng nhập!").setMessage("Hãy đăng nhập để comment!")
							.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									if (!type_SongAlbum.equals(TagName.Comment_typeVideo)) {
										((MainActivity) context).mSilidingUP.hidePanel();
										((MainActivity) context).switchContent(AccountLoginFragment.class.getName());
									} else {
										AccountLoginDialog accountLoginDialog = new AccountLoginDialog();
										accountLoginDialog.show(((VideoPlayActivity) context).getSupportFragmentManager(), null);
									}
								}
							}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									// do nothing
								}
							}).setIcon(android.R.drawable.ic_dialog_alert).show();
				}
			}
		});
		// if(songObject!=null)
		// showView(songObject.getFormNet());
		mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
		mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				loadingMore = false;
				listViewComnent.stopProgressBar();
				stop();
				new listCommentService().execute("");
			}
		});
		mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

	}

	class sendCommentService extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.sendCommnets(audioID, type_SongAlbum, "kenhnhac", params[0], PreferenceUtils.getString(context, TagName.KeyPreference_user));
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			new listCommentService().execute(audioID);
		}
	}

	class loginService extends AsyncTask<String, String, String> {
		ProgressDialog progressDialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... param) {
			String str = WServiceLib.login(param[0], param[1]);
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!progressDialog.isShowing())
				progressDialog.show();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null) {
				try {
					JsonReader.loginReader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject.getCODE().equals("0")) {
				ImageLoader.getInstance().loadImage(HomeData.homeAccount.getAVATAR(), new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						super.onLoadingComplete(imageUri, view, loadedImage);
						PreferenceUtils.putString(context, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
						PreferenceUtils.putString(context, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
						PreferenceUtils.putString(context, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
						PreferenceUtils.putString(context, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
						PreferenceUtils.putString(context, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
						// PreferenceUtils.putString(context,
						// TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
						PreferenceUtils.putString(context, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
						TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
						alertDialog.dismiss();
					}
				});
			} else
				TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
		}
	}

	class listCommentService extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.listCommnets(audioID, type_SongAlbum, page, pageSize);
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					listComment = JsonReader.listComment(result);
					if (listComment != null)
						adapter.setList(listComment);
					// listViewComnent.stopProgressBar();
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}

	public void stop() {
		listViewComnent.stopRefresh();
		listViewComnent.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		if (!loadingMore) {
			xpage += 1;
			if (songObject != null) {
				if (songObject.getFormNet())
					new listCommentService().execute(audioID);
			} else
				new listCommentService().execute(audioID);
		} else
			stop();
	}

	@Override
	public void onLoadMore() {
		if (!loadingMore) {
			xpage += 1;
			if (songObject != null) {
				if (songObject.getFormNet())
					new listCommentService().execute(audioID);
			} else
				new listCommentService().execute(audioID);
		} else
			stop();
	}
}